package com.david.cloud.user.controller;


import cn.hutool.extra.servlet.ServletUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.david.cloud.user.entity.Token;
import com.david.cloud.user.entity.User;
import com.david.cloud.user.service.ITokenService;
import com.david.cloud.user.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author david
 * @since 2020-05-24
 */
@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    private IUserService userService;
    @Autowired
    private ITokenService tokenService;

    @RequestMapping("/register/{email}/{password}/{code}")
    public User register(@PathVariable String email, @PathVariable String password, @PathVariable String code, HttpServletResponse response) {
        Boolean registered = isRegistered(email);
        if (registered) {
            throw new RuntimeException("请勿重复注册");
        }
        User user = userService.register(email, password, code);
        return addCookie(response, user);
    }

    @RequestMapping("/info")
    public String info(HttpServletRequest request) {
//        Cookie token = ServletUtil.getCookie(request, "token");
//        if (token == null) {
//            throw new RuntimeException("token is null");
//        }
        String token = request.getHeader("token");
        Token t = tokenService.getByToken(token);
        return t.getEmail();
    }

    @RequestMapping("/isRegistered/{email}")
    public Boolean isRegistered(@PathVariable String email) {
        int count = userService.count(Wrappers.<User>lambdaQuery().eq(User::getEmail, email));
        return count > 0;
    }

    @RequestMapping("/login/{email}/{password}")
    public User login(@PathVariable String email, @PathVariable String password, HttpServletResponse response) {
        User user = userService.login(email, password);
        return addCookie(response, user);
    }

    private User addCookie(HttpServletResponse response, User user) {
        if (user == null) {
            return null;
        }
        Token token = user.getToken();
        Cookie cookie = new Cookie("token", token.getToken());
        response.addCookie(cookie);
        return user;
    }
}
